package com.ygxsk.carhome.ui.usercenter;

import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.response.SmsCodeBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.ClearEditText;
import com.ygxsk.carhome.views.ClearEditTextUser;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2024/1/29  9:37
 * @Description:找回密码的界面
 */
public class CallBackPsdActivity extends ErrorActivity {

    //输入修改的新密码
    @BindView(R.id.etnewpasswordcallback)
    ClearEditTextUser etNewPassWordCallBack;

    //确认修改的新密码
    @BindView(R.id.etnewpasswordconfirmcallback)
    ClearEditTextUser etNewPassWordConfirmCallBack;

    //手机号输入
    @BindView(R.id.edittextphonenumbercallback)
    ClearEditText editTextPhoneNumberCallback;

    //短信验证码输入
    @BindView(R.id.edittextcoderesultcallback)
    ClearEditText editTextCodeResultCallback;

    //按钮的获取验证码
    @BindView(R.id.btn_get_verify_code_againinchaphone)
    RoundTextView btnGetCodeagain;

    //---------------------------------------------------------
    /**
     * 该界面的所有提示通用
     */
    private AlertView mAlertView;

    //手机号的上传；
    private String phoneNumber_upLoad;
    //验证码的上传
    private String smsCode_upLoad;
    //新密码的上传
    private String password_upLoad;
    //密码确认
    private String password_confirm_upLoad;

    /**
     * 短信验证码的倒计时目前手写为60
     */
    private CountDownTimer downTimer;
    /**
     * 倒计时的时间内容，默认是60毫秒
     */
    private int timeTotal = 60;

    /**
     * 验证码的数字个数，默认是4个，可能是会有6个的情况
     */
    private int codeCount = 4;

    /*
     * @Author:itchenqi
     * @Time:2022-04-06  14:08
     * @Description:登录界面的对倒计时的修改，改为动态从服务器获取
     */
    private class MyCountDownTimerInLogin extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MyCountDownTimerInLogin(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        /**
         * Callback fired on regular interval.
         *
         * @param millisUntilFinished The amount of time until finished.
         */
        @Override
        public void onTick(long millisUntilFinished) {

            if (btnGetCodeagain != null) {
                btnGetCodeagain.setText(getString(R.string.gainsmscoderemain) + millisUntilFinished / 1000 + getString(R.string.unit_time_seconds));
            }

        }

        /**
         * Callback fired when the time is up.
         */
        @Override
        public void onFinish() {

            if (btnGetCodeagain != null) {
                btnGetCodeagain.setEnabled(true);
                btnGetCodeagain.setText(getString(R.string.gainsmscodeagin));//请重新获取
            }

        }
    }

    private void method_check() {

        //校验 是否输入 即将修改的密码
        password_upLoad = etNewPassWordCallBack.getText().toString().trim();
        //再次确认的密码
        password_confirm_upLoad = etNewPassWordConfirmCallBack.getText().toString().trim();
        //调用发送验证码接口，且更改后边倒计时文字。
        if (editTextPhoneNumberCallback != null) {
            phoneNumber_upLoad = editTextPhoneNumberCallback.getText().toString().trim();
        } else {
            phoneNumber_upLoad = "";
        }

        //---------------------------------------------------------------------------------------------
        //校验密码是否是没有输入  请输入新密码
        if (TextUtils.isEmpty(password_upLoad)) {
            //如果房屋号是空的，那么就提示
            CommUtils.checkDialog(mAlertView);
            mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.alert_psd_input), true);
            mAlertView.show();
            return;
        }

        //校验新密码 是否符合规则：
        //校验新密码是否符合规则
        if (!methodCheckNewPassrod(password_upLoad)) {
            //新密码输入：8-20位数字和字母组合~
            //CommUtils.method_showAlertViewSingle(mActivityInstance, "提示", "新密码请输入：8-20位数字和字母组合~", true);
            //string抽取的字符串是："密码长度为8-20位，且至少包含字母、数字或字符~!@#$%^&*_中的两种组成！"
            CommUtils.method_showAlertViewSingle(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.password_rules), true);

            return;
        }


        if (TextUtils.isEmpty(password_confirm_upLoad)) {
            //如果房屋号是空的，那么就提示
            CommUtils.checkDialog(mAlertView);
            mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.alert_psd_input_confirm), true);
            mAlertView.show();
            return;
        }
        //---------------------------------------------------------------------------------------------------------------------------
        if (TextUtils.isEmpty(phoneNumber_upLoad)) {
            CommUtils.checkDialog(mAlertView);
            mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.alert_input_phonenumber), true);
            mAlertView.show();
            return;
        }


        if (!TextUtils.isEmpty(phoneNumber_upLoad)) {
            if (!RegexUtils.isMobileSimple(phoneNumber_upLoad)) {//电话格式 校验
                CommUtils.checkDialog(mAlertView);
                mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.alert_phone_formerror), true);
                mAlertView.show();
                return;
            }

            if (!RegexUtils.isMobileExact(phoneNumber_upLoad)) {//精确验证手机号
                CommUtils.checkDialog(mAlertView);
                mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.alert_phone_effective), true);
                mAlertView.show();
                return;
            }
        }

    }


    @OnClick({R.id.btn_get_verify_code_againinchaphone,//验证码
            R.id.btn_submit_inchaphone//提交验证码信息
    })
    public void clickInCallBackPsd(View view) {

        switch (view.getId()) {

            case R.id.btn_get_verify_code_againinchaphone: {//获取验证码

                // TODO: 2023-09-06 14:59 校验是否输入
                KeyboardUtils.hideSoftInput(mActivityInstance);

                method_check();
                //---------------------------------------------------------------------------------------------------------------------------
                //---------------------------------------------------------------------------------------------------------------------------
                //发送验证码接口调用
                if (NetworkUtils.isConnected()) {//如果联网成功则,先验证 手机号，然后再次发送验证码

                    method_upload_phone_for_getSmsCode();

                } else {
//                    CommUtils.displayToastShort(mActivityInstance, ConstantApi.NETWORKFAIL);
                    ToastUtils.showShort(getString(R.string.network_error_inside));
                }

                break;
            }

            case R.id.btn_submit_inchaphone: {//提交按钮

                //提交按钮的前边几项都要校验
                // TODO: 2023-09-06 14:59 校验是否输入 以上的全部参数
                method_check();

                //---------------------------------------------------------------------------------------------------------------------------
                //校验验证码
                smsCode_upLoad = editTextCodeResultCallback.getText().toString().trim();

                if (TextUtils.isEmpty(smsCode_upLoad)) {//请输入验证码
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.alert_psd_input_smscode), true);
                    mAlertView.show();
                    return;
                }

                //发送验证码接口调用
                if (NetworkUtils.isConnected()) {//如果联网成功则,先验证 手机号，然后再次发送验证码

                    method_upload_phoneAndSmsCode();

                } else {
//                    CommUtils.displayToastShort(mActivityInstance, ConstantApi.NETWORKFAIL);
                    ToastUtils.showShort(getString(R.string.network_error_inside));
                }


                break;
            }

        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        //第一次创建一个默认的
        downTimer = new MyCountDownTimerInLogin(1000 * timeTotal, 1000);

        //retain

    }

    @Override
    public Resources getResources() {
        return super.getResources();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_call_back_psd;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.callback_psd));
        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //右侧添加下载二维码
//        toolbarHelper.setLayoutRight(true, 0, "更多", new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //二维码图片，下载链接，和apk链接信息
//            }
//        });

        toolbarHelper.setLayoutRight(false, 0, "", null);

    }

    @Override
    protected void onClickNodata(View v) {

    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void gainDatas() {

    }

    @Override
    protected void methodBack() {

        ActivityUtils.finishActivity(this);

    }


    //校验 新密码 是否合规?
    private boolean methodCheckNewPassrod(String newPassWord) {
        //https://blog.csdn.net/moye666/article/details/117529870

        //密码长度为8-20位，且至少包含字母、数字或字符~!@#$%^&*_中的两种组成！

        //String value = "^[0-9a-zA-Z~!@#$%^&*_]{8,20}$";
//        String value = "^[0-9a-zA-Z~!@#$%^&*_]{8,20}$";

        String value = "^(?![0-9]+$)(?![a-zA-Z]+$)(?![_\\W]+$)[0-9A-Za-z_\\W]{8,20}$";

        //Pattern p = Pattern.compile(value);
        //Matcher m = p.matcher(newPassWord);

        boolean result = RegexUtils.isMatch(value, newPassWord);

        return result;

    }

    private void method_upload_phone_for_getSmsCode() {

        HashMap<String, Object> jsonObject = new HashMap<>();
        //jsonObject.put(ConstantApi.SHOPINFOID, mSession.getShopInfoId());

        jsonObject.put(Parameterkey.phonenumber, phoneNumber_upLoad);


        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_SENDSMSCODE);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.sendSmsCodeUrl);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(jsonObject);

        //做界面展示给用户的
        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .sendSmsCode(RequestBody.create(JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(CallBackPsdActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<SmsCodeBean>(ConstantApi.IS_ACTIVITY_ITSELF, CallBackPsdActivity.this) {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //{"code":400,"msg":"修改密码失败，旧密码错误","data":""}
//                        if (TextUtils.equals(serverCode, ConstantSign.RESPONSE_400)) {
//
//                            CommUtils.checkDialog(alertViewDialogSure);
//                            alertViewDialogSure = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, serverMessage, true);
//                            alertViewDialogSure.show();
//
//                        } else {
//
//                            if (!TextUtils.isEmpty(serverMessage)) {
//                                ToastUtils.showLong(serverMessage);
//                            }
//
//                        }

                        buttonAgain();

                    }
                }))
                .subscribe(new Consumer<SmsCodeBean>() {
                    @Override
                    public void accept(SmsCodeBean smsCodeBean) throws Exception {

//                        {
//                            "code": 200,
//                                "data": {
//                                "codeLength": 4,
//                                    "time": 60,
//                                    "timeUnit": "SECONDS"
//                           },
//                            "msg": "操作成功"
//                        }

                        //拉取到的 信息
                        if (smsCodeBean != null) {

                            timeTotal = smsCodeBean.getTime();

                            codeCount = smsCodeBean.getCodeLength();

                            //2022-4-6 14:12:05 这里是动态的关键
                            if (timeTotal != 0) {
                                downTimer = new MyCountDownTimerInLogin(1000 * timeTotal, 1000);
                            }

                            //此刻开始倒计时
                            if (downTimer != null) {
                                downTimer.start();
                                btnGetCodeagain.setEnabled(false);
                            }


                        }


                    }
                    //自定义
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException e) {

//                        buttonAgain();

                    }
                });


    }

    //提交验证码接口
    private void method_upload_phoneAndSmsCode() {

        HashMap<String, Object> jsonObject = new HashMap<>();
        //jsonObject.put(ConstantApi.SHOPINFOID, mSession.getShopInfoId());

        jsonObject.put(Parameterkey.phonenumber, phoneNumber_upLoad);
        jsonObject.put(Parameterkey.smsCode, smsCode_upLoad);
        jsonObject.put(Parameterkey.password, password_upLoad);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_APPSMSCHANGEPWD);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.appSmsChangePwdUrl);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(jsonObject);

        //做界面展示给用户的
        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .appSmsChangePwd(RequestBody.create(JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(CallBackPsdActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>(ConstantApi.IS_ACTIVITY_ITSELF, CallBackPsdActivity.this) {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            CommUtils.method_showAlertViewSingle(mActivityInstance, ConstantSign.ALERT_TITLE, serverMessage, true);
                        }

                    }
                }))
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Exception {

                        //{"code":200,"msg":"操作成功","data":true}
                        CommUtils.checkDialog(mAlertView);

                        //提示提交成功，然后1秒后关闭界面.
                        methodSubmitSuccess(mActivityInstance, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                                if (ActivityUtils.isActivityAlive(CallBackPsdActivity.this)) {
                                    ActivityUtils.finishActivity(CallBackPsdActivity.this);
                                }

                            }
                        });

                    }
                    //自定义
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException e) {

//                        buttonAgain();

                    }
                });


    }


    private void buttonAgain() {

        if (downTimer != null) {
            downTimer.cancel();
            btnGetCodeagain.setEnabled(true);
            btnGetCodeagain.setText(R.string.gainsmscodeagin);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //倒计时 ：
        //关闭验证码的倒计时
        if (downTimer != null) {
            downTimer.cancel();
            downTimer = null;
        }

        //确认修改的新密码
        if (etNewPassWordCallBack != null) {
            etNewPassWordCallBack.setText("");
        }

        //确认再次修改的密码
        if (etNewPassWordConfirmCallBack != null) {
            etNewPassWordConfirmCallBack.setText("");
        }

        //手机号录入
        if (editTextPhoneNumberCallback != null) {
            editTextPhoneNumberCallback.setText("");
        }

        //清空验证码的文本框：
        if (editTextCodeResultCallback != null) {
            editTextCodeResultCallback.setText("");
        }

    }
}